package com.yuanqi.springboot_banksystem.controller;

import com.yuanqi.springboot_banksystem.entity.UserEntity;
import com.yuanqi.springboot_banksystem.service.UserService;
import com.yuanqi.springboot_banksystem.utils.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;


@Controller
public class UserController extends BaseController{

    @Autowired
    UserService userService;

    @PostMapping("/register")
    public String register(Model model, UserEntity user){

        if (userService.selectUser(user.getUsername())!=null){
            model.addAttribute("loginmsg", "用户名已被注册");
            return "loginPage";
        }

        /**
         * 测试阶段：默认设置用户余额为1000000,在service层
         */

        /**
         * 注册
         */
        Boolean register = userService.register(user);
        if (register){
            model.addAttribute("loginmsg", "注册成功");
            return "loginPage";
        }
        else {
            model.addAttribute("registermsg", "注册失败");
            return "registerPage";
        }
    }

    @PostMapping("/login")
    public String login(Model model, UserEntity user, HttpServletRequest httpServletRequest) {

        String username = user.getUsername();
        String password = user.getPassword();

        Boolean login = userService.login(username, password);

        /**
         * 密码正确，再通过shiro登录
         */
        if (login) {

            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(username, password));

            UserEntity userEntity = userService.selectUser(username);
            userEntity.setPassword(null);
            userEntity.setSalt(null);
            httpServletRequest.getSession().setAttribute("user", userEntity);
            if (userEntity.getRole().equals("user")){
                return "indexPage";
            }
            return "adminIndexPage";
        }

        model.addAttribute("loginmsg", "用户名或密码错误");

        return "loginPage";
    }

    @RequestMapping("/queryself")
    public String queryself(HttpServletRequest httpServletRequest){
        String username = (String)SecurityUtils.getSubject().getPrincipal();

        UserEntity userEntity = userService.selectUser(username);

        httpServletRequest.getSession().setAttribute("user", userEntity);

        return "queryselfPage";
    }

//    @PostMapping("/update")
//    public String update(UserEntity user, Model model, HttpServletRequest httpServletRequest){
//
//
//        String username = (String)SecurityUtils.getSubject().getPrincipal();
//
//        UserEntity userEntity = userService.selectUser(username);
//
//        if(!StringUtils.isEmpty(user.getPassword())){
//            userEntity.setPassword(MD5Util.getMd5Password(user.getPassword(), userEntity.getSalt()));
//        }
//        if(!StringUtils.isEmpty(user.getTel())){
//            userEntity.setTel(user.getTel());
//        }
//
//        Boolean aBoolean = userService.updateUser(userEntity);
//
//        if(aBoolean){
//            model.addAttribute("updatemsg", "修改成功");
//        }
//        else {
//            model.addAttribute("updatemsg", "修改失败");
//        }
//
//        return "updatePage";
//    }

    @PostMapping("/updatePassword")
    public String updatePassword(String password, Model model){


        String username = (String)SecurityUtils.getSubject().getPrincipal();

        UserEntity userEntity = userService.selectUser(username);

        if(StringUtils.isEmpty(password)){
            model.addAttribute("updatepasswordmsg", "密码为空");
            return "updatePasswordPage";
        }
        userEntity.setPassword(MD5Util.getMd5Password(password, userEntity.getSalt()));
        Boolean aBoolean = userService.updateUser(userEntity);

        if(aBoolean){
            model.addAttribute("updatepasswordmsg", "修改成功");
        }
        else {
            model.addAttribute("updatepasswordmsg", "修改失败");
        }

        return "updatePasswordPage";
    }

    @PostMapping("/updateTel")
    public String updateTel(String tel, Model model){


        String username = (String)SecurityUtils.getSubject().getPrincipal();

        UserEntity userEntity = userService.selectUser(username);

        if(StringUtils.isEmpty(tel)){
            model.addAttribute("updatetelmsg", "手机号为空");
            return "updateTelPage";
        }
        userEntity.setTel(tel);
        Boolean aBoolean = userService.updateUser(userEntity);

        if(aBoolean){
            model.addAttribute("updatetelmsg", "修改成功");
        }
        else {
            model.addAttribute("updatetelmsg", "修改失败");
        }

        return "updateTelPage";
    }

    @RequestMapping("/verify")
    public String verify(Model model){

        String username = (String)SecurityUtils.getSubject().getPrincipal();

        UserEntity userEntity = userService.selectUser(username);

        if (userEntity.getBanlance()<0){

            userEntity.setBanlance(0.0);

            model.addAttribute("verifymsg","数据异常，已重置！");
            return "verifyPage";
        }
        model.addAttribute("verifymsg","校验成功，数据正常");
        return "verifyPage";
    }

    @PostMapping("/transfermoney")
    public String transfermoney(String tousername, String money, Model model){

        String username = (String)SecurityUtils.getSubject().getPrincipal();

        UserEntity userEntity = userService.selectUser(username);

        int intmoney = Integer.parseInt(money);

        UserEntity touser = userService.selectUser(tousername);
        if (StringUtils.isEmpty(touser)) {
            model.addAttribute("transfermoneymsg", "该账户不存在。");
            return "transfermoneyPage";
        } else if (userEntity.getIs_cold() == 1) {
            model.addAttribute("transfermoneymsg", "您的账户处于冻结状态，无法汇款。");
            return "transfermoneyPage";
        } else if (touser.getIs_cold() == 1) {
            model.addAttribute("transfermoneymsg", "该账户处于冻结状态，无法汇款。");
            return "transfermoneyPage";
        } else if (userEntity.getBanlance() < intmoney) {
            model.addAttribute("transfermoneymsg", "您的余额不足。");
            return "transfermoneyPage";
        }
        userEntity.setBanlance(userEntity.getBanlance() - intmoney);
        touser.setBanlance(touser.getBanlance() + intmoney);
        Boolean aBoolean = userService.updateUser(userEntity);
        Boolean aBoolean1 = userService.updateUser(touser);
        if (aBoolean && aBoolean1) {
            model.addAttribute("transfermoneymsg", "转账成功！");
        } else {
            model.addAttribute("transfermoneymsg", "转账失败！请联系管理人员");
        }

        return "transfermoneyPage";

    }

    @RequestMapping("/docold")
    public String docold(Model model){
        String username = (String)SecurityUtils.getSubject().getPrincipal();

        UserEntity userEntity = userService.selectUser(username);

        int cold = userEntity.getIs_cold();

        if (cold == 1){
            userEntity.setIs_cold(0);
        }
        else{
            userEntity.setIs_cold(1);
        }

        Boolean aBoolean = userService.updateUser(userEntity);

        if (aBoolean){
            model.addAttribute("coldmsg", "操作成功。");
            if (cold == 1){
                model.addAttribute("cold", "false");
            }
            else {
                model.addAttribute("cold", "true");
            }
        }
        else {
            model.addAttribute("coldmsg", "操作失败。");
        }

        return "coldPage";
    }

    @PostMapping("/revoke")
    public String revoke(Model model, String tel){

        String username = (String)SecurityUtils.getSubject().getPrincipal();

        UserEntity userEntity = userService.selectUser(username);

        if (!tel.equals(userEntity.getTel())){
            model.addAttribute("revokemsg", "电话错误，身份验证失败。");
            return "revokePage";
        }
        if(userEntity.getBanlance()>0){
            model.addAttribute("revokemsg", "您的账户余额不为0，无法注销。");
            return "revokePage";
        }

        userEntity.setIs_delete(1);
        Boolean aBoolean = userService.updateUser(userEntity);
        if(aBoolean){
            model.addAttribute("loginmsg", "注销成功。");
            return "redirect:/login";
        }
        else{
            model.addAttribute("revokemsg", "注销失败。");
            return "revokePage";
        }
    }

    @RequestMapping("/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "loginPage";
    }

    @PostMapping("/queryuser")
    public String queryuser(Model model, String username, HttpServletRequest httpServletRequest){

        UserEntity userEntity = userService.selectUser(username);

        if (StringUtils.isEmpty(userEntity)){
            model.addAttribute("querymsg", "该用户不存在。");
            return "queryuserPage";
        }
        model.addAttribute("querymsg", "查询成功。");
        httpServletRequest.getSession().setAttribute("selectuser", userEntity);
        return "queryuserPage";
    }

    @PostMapping("/updateuser")
    public String updateuser(Model model, UserEntity user, HttpServletRequest httpServletRequest){

        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user)) {
            model.addAttribute("updateusermsg", "错误输入。");
            return "updateuserPage";
        }

        UserEntity newuser = userService.selectUser(user.getUsername());

        if (StringUtils.isEmpty(user.getPassword()) && StringUtils.isEmpty(user.getTel())){
            model.addAttribute("updateusermsg", "请输入要修改的信息。");
            return "updateuserPage";
        }


        if (newuser.getRole()=="admin") {
            model.addAttribute("updateusermsg", "您没有此权限。");
            return "updateuserPage";
        }


        String password = user.getPassword();
        String tel = user.getTel();


        if(password!=null && !password.equals("")){
            newuser.setPassword(MD5Util.getMd5Password(password, newuser.getSalt()));
        }
        if(tel!=null && !tel.equals("")){
            newuser.setTel(tel);
        }
        Boolean aBoolean = userService.updateUser(newuser);
        if(aBoolean){
            model.addAttribute("updateusermsg", "修改成功");
        }
        else {
            model.addAttribute("updateusermsg", "修改失败");
        }

        return "updateuserPage";
    }

    @PostMapping("/adduser")
    public String adduser(Model model, UserEntity user){


        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user)) {
            model.addAttribute("addusermsg", "错误输入。");
            return "adduserPage";
        }

        UserEntity newuser = userService.selectUser(user.getUsername());

        if (userService.selectUser(user.getUsername())!=null){
            model.addAttribute("addusermsg", "此用户名已被注册");
            return "adduserPage";
        }

        user.setPassword(MD5Util.getMd5Password(user.getPassword(), MD5Util.getRandomSalt()));

        Boolean register = userService.register(user);
        if(register){
            model.addAttribute("addusermsg", "添加成功");
            return "adduserPage";
        }
        else {
            model.addAttribute("addusermsg", "添加失败");
            return "adduserPage";
        }
    }

    @PostMapping("/deleteuser")
    public String deleteuser(String username,Model model){

        UserEntity user = userService.selectUser(username);

        if (StringUtils.isEmpty(username)) {
            model.addAttribute("deleteusermsg", "错误输入。");
        }
        if (StringUtils.isEmpty(user)){
            model.addAttribute("deleteusermsg", "错误输入。");
        }
        if (user.getBanlance()>0){
            model.addAttribute("deleteusermsg", "该账户余额不为0，无法删除。");
            return "deleteUserPage";
        }

        user.setIs_delete(1);

        Boolean aBoolean = userService.updateUser(user);
        if(!aBoolean){
            model.addAttribute("deleteusermsg", "删除失败");
            return "deleteUserPage";
        }
        else {
            model.addAttribute("deleteusermsg", "删除成功");
            return "deleteUserPage";
        }
    }

}
